#!/bin/bash
# 创建目录
mkdir -p /usr/local/docker-redis/redis-cluster
# 切换至指定目录
cd /usr/local/docker-redis/redis-cluster/
# 编写 redis-cluster.tmpl 文件
tee redis-cluster.tmpl <<-'EOF'
port ${PORT}
requirepass 1234
masterauth 1234
protected-mode no
daemonize no
appendonly yes
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 15000
cluster-announce-ip ${IP}
cluster-announce-port ${PORT}
cluster-announce-bus-port 1${PORT}
EOF
# 创建相关目录或文件
for port in `seq 6374 6376`; do \
  mkdir -p ${port}/conf \
  && PORT=${port} IP=$1 envsubst < redis-cluster.tmpl > ${port}/conf/redis.conf \
  && mkdir -p ${port}/data;\
done
tree /usr/local/docker-redis/redis-cluster/
echo "============================== $1 =============================="
cat /usr/local/docker-redis/redis-cluster/637{4..6}/conf/redis.conf

# 创建docker-compose.yaml
tee docker-compose.yml <<-'EOF'
# 描述 Compose 文件的版本信息
version: "3.3"

# 定义服务，可以多个
services:
  redis-6374: # 服务名称
    image: redis # 创建容器时所需的镜像
    container_name: redis-6374 # 容器名称
    restart: always # 容器总是重新启动
    network_mode: "host" # host 网络模式
    volumes: # 数据卷，目录挂载
      - /usr/local/docker-redis/redis-cluster/6374/conf/redis.conf:/usr/local/etc/redis/redis.conf
      - /usr/local/docker-redis/redis-cluster/6374/data:/data
    command: redis-server /usr/local/etc/redis/redis.conf # 覆盖容器启动后默认执行的命令

  redis-6375:
    image: redis
    container_name: redis-6375
    network_mode: "host"
    volumes:
      - /usr/local/docker-redis/redis-cluster/6375/conf/redis.conf:/usr/local/etc/redis/redis.conf
      - /usr/local/docker-redis/redis-cluster/6375/data:/data
    command: redis-server /usr/local/etc/redis/redis.conf

  redis-6376:
    image: redis
    container_name: redis-6376
    network_mode: "host"
    volumes:
      - /usr/local/docker-redis/redis-cluster/6376/conf/redis.conf:/usr/local/etc/redis/redis.conf
      - /usr/local/docker-redis/redis-cluster/6376/data:/data
    command: redis-server /usr/local/etc/redis/redis.conf
EOF

# 创建并启动所有容器
docker-compose up -d
docker-compose ps

# 进入容器
# docker exec -it redis-6371 bash
# 切换至指定目录
# cd /usr/local/bin/
# 执行集群创建命令
# redis-cli -a 1234 --cluster create 192.168.10.10:6371 192.168.10.10:6372 192.168.10.10:6373 192.168.10.11:6374 192.168.10.11:6375 192.168.10.11:6376 --cluster-replicas 1

#cat /usr/local/docker-redis/redis-cluster/redis-cluster.tmpl
# port：节点端口；
# requirepass：添加访问认证；
# masterauth：如果主节点开启了访问认证，从节点访问主节点需要认证；
# protected-mode：保护模式，默认值 yes，即开启。开启保护模式以后，需配置 bind ip或者设置访问密码；关闭保护模式，外部网络可以直接访问；
# daemonize：是否以守护线程的方式启动（后台启动），默认 no；
# appendonly：是否开启 AOF 持久化模式，默认 no；
# cluster-enabled：是否开启集群模式，默认 no；
# cluster-config-file：集群节点信息文件；
# cluster-node-timeout：集群节点连接超时时间；
# cluster-announce-ip：集群节点 IP，填写宿主机的 IP；
# cluster-announce-port：集群节点映射端口；
# cluster-announce-bus-port：集群节点总线端口。
